// src/core/observer/index.ts

class Observer<T extends object> {
  public value: T;
  private __ob__: Observer<T>;

  constructor(value: T) {
    this.value = value;
    this.__ob__ = this;

    // 使用 Proxy 替代原 def 函数
    Object.defineProperty(value, '__ob__', {
      enumerable: false,
      configurable: false,
      value: this
    });

    if (Array.isArray(value)) {
      // 数组特殊处理逻辑（可选）
    } else {
      this.walk(value);
    }

    // 返回 Proxy 实例以支持链式访问
    return new Proxy(this, {
      get(target, key) {
        if (key === '__ob__') return target;
        return Reflect.get(target.value, key);
      },
      set(target, key, value) {
        return Reflect.set(target.value, key, value);
      }
    });
  }

  walk(obj: T): void {
    const keys = Object.keys(obj) as Array<keyof T>;
    for (const key of keys) {
      this.defineReactive(obj, key, obj[key]);
    }
  }

  private defineReactive(obj: object, key: any, val: any): void {
    if (val !== null && typeof val === 'object') {
      val = new Observer(val);
    }
    Object.defineProperty(obj, key, {
      enumerable: true,
      configurable: true,
      get() {
        console.log(`Getter: ${key}`);
        return val;
      },
      set(newVal) {
        if (newVal === val) return;
        console.log(`Setter: ${key} <=`, newVal);
        val = newVal;
      }
    });
  }
}

// 导出类型定义
export default Observer;